//
//  BMHStoreObserver.m
//  BMHVideoMain
//
//  Created by feng song on 2017/11/8.
//  Copyright © 2017年 BAOMIHUA.COM. All rights reserved.
//  AppStore内购支付

#import "BMHStoreObserver.h"
//沙盒测试环境验证
#define SANDBOX  @"https://sandbox.itunes.apple.com/verifyReceipt"
//正式环境验证
#define AppStore @"https://buy.itunes.apple.com/verifyReceipt"


@implementation BMHStoreObserver

+ (BMHStoreObserver *)sharedInstance
{
    static dispatch_once_t onceToken;
    static BMHStoreObserver * storeObserverSharedInstance;
    
    dispatch_once(&onceToken, ^{
        storeObserverSharedInstance = [[BMHStoreObserver alloc] init];
    });
    return storeObserverSharedInstance;
}


- (instancetype)init
{
    self = [super init];
    if (self != nil)
    {
        _productsPurchased = [[NSMutableArray alloc] initWithCapacity:0];
        
    }
    return self;
}
#pragma -
#pragma mark - 去苹果服务器请求产品信息

-(void)buy:(NSString*)productId withPayMonyNum:(NSString *)money andPayOrder:(NSString *)order;
{
    
    self.purchasedID              = productId;
    self.payMoney                 = money;
    self.payOrder                 = order;
    self.productsPurchased        = [[NSMutableArray alloc] initWithObjects:productId,nil];
    NSSet             *productSet = [NSSet setWithArray:self.productsPurchased];
    SKProductsRequest *request    = [[SKProductsRequest alloc] initWithProductIdentifiers:productSet];
    request.delegate              = self;
    [request start];
}
#pragma -
#pragma mark- SKProductsRequestDelegate
/**
 收到产品返回信息

 @param request 请求方法方式
 @param response 服务器请求
 */
-(void)productsRequest:(SKProductsRequest*)request didReceiveResponse:(SKProductsResponse*)response
{
    NSArray*productArr=response.products;
    if([productArr count]==0)
    {
        [MBProgressHUD hideHUD];
        BMHLog(@"没有该商品");
        return;
    }
    BMHLog(@"productId = %@",response.invalidProductIdentifiers);
    BMHLog(@"产品付费数量 = %zd",productArr.count);
    SKProduct*p=nil;
    for(SKProduct*pro in productArr)
    {
        BMHLog(@"description:%@",[pro description]);
        BMHLog(@"localizedTitle:%@",[pro localizedTitle]);
        BMHLog(@"localizedDescription:%@",[pro localizedDescription]);
        BMHLog(@"price:%@",[pro price]);
        BMHLog(@"productIdentifier:%@",[pro productIdentifier]);
        if([pro.productIdentifier isEqualToString:self.purchasedID])
        {
            p=pro;
        }
    }
    
    SKPayment* payment= [SKPayment paymentWithProduct:p];//发送内购请求
    
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}
#pragma -
#pragma mark- SKRequestDelegate
/**
 请求完成方法

 @param request 完成之后
 */
-(void)requestDidFinish:(SKRequest*)request
{
    [MBProgressHUD hideHUD];
}

/**
 请求失败方法

 @param requestdidFail 请求失败
 @param error 错误
 */
-(void)request:(SKRequest*)requestdidFail WithError:(NSError*)error
{
    [MBProgressHUD hideHUD];
    [MBProgressHUD showContent:@"支付失败"];
}

#pragma mark- SKPaymentTransactionObserver监听购买结果
/**
 监听购买结果

 @param queue 加入购买对列
 @param transactions 完成
 */
-(void)paymentQueue:(SKPaymentQueue*)queue updatedTransactions:(NSArray*)transactions
{
    for(SKPaymentTransaction*tran in transactions)
    {
        switch(tran.transactionState)
        {
            case SKPaymentTransactionStatePurchased://交易完成
                
                // 发送到苹果服务器验证凭证
                [MBProgressHUD hideHUD];
                [self verifyPruchase];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                
                break;
            case SKPaymentTransactionStatePurchasing://商品添加进列表
                
                break;
            case SKPaymentTransactionStateRestored://购买过
                
                // 发送到苹果服务器验证凭证
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                
                break;
            case SKPaymentTransactionStateFailed://交易失败
                
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                [MBProgressHUD showError:@"购买失败"];
                
                break;
            default:
                break;
        }
    }
}

#pragma mark - 发送到苹果服务器验证凭证
/**
 *  验证购买，避免越狱软件模拟苹果请求达到非法购买问题
 *
 */
- (void)verifyPruchase
{
    [self appStoreVerify];
    
}

#pragma mark -
#pragma mark -正式验证

/**
 验证步骤:
          1.获取到苹果返回的交易凭据
          2.通过凭据向苹果服务器验证
          3.返回状态status值
          4.status = 0，验证成功(代表是AppStore正式用户付款)
          5.status = 21007，验证失败(代表是沙盒测试用户)，继续NEXT
 */
-(void)appStoreVerify
{
    
    // 验证凭据，获取到苹果返回的交易凭据
    // appStoreReceiptURL iOS7.0增加的，购买交易完成后，会将凭据存放在该地址
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    // 从沙盒中获取到购买凭据
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    // 发送网络POST请求，对购买凭据进行验证
    NSURL *url = [NSURL URLWithString:AppStore];
    // 国内访问苹果服务器比较慢，timeoutInterval需要长一点
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    request.HTTPMethod = @"POST";
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    
    NSString *payload = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", encodeStr];
    NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];
    
    request.HTTPBody = payloadData;
    // 提交验证请求，并获得官方的验证JSON结果
    //NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSOperationQueue *opQueue = [NSOperationQueue new];
    [NSURLConnection sendAsynchronousRequest:request queue:opQueue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSLog(@"test1:%@",response);
        // 官方验证结果为空验证失败
        if (data == nil)
        {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"验证失败"];
            return;
        }
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        //验证成功
        if ([[dict objectForKey:@"status"] integerValue] == 0) {
            // 比对字典中以下信息基本上可以保证数据安全
            // bundle_id&application_version&product_id&transaction_id
            NSLog(@"购买成功");
            [MBProgressHUD hideHUD];
            [self addRoseApplePurchase];
            
        }else if ([[dict objectForKey:@"status"] integerValue] == 21007){
            [self sandBoxVerify];
            
        }
        
    }];

    
}

#pragma mark -
#pragma mark -沙盒验证

/**
 沙盒测试API
 */
-(void)sandBoxVerify
{
    // 验证凭据，获取到苹果返回的交易凭据
    // appStoreReceiptURL iOS7.0增加的，购买交易完成后，会将凭据存放在该地址
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    // 从沙盒中获取到购买凭据
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    // 发送网络POST请求，对购买凭据进行验证
    NSURL *url = [NSURL URLWithString:SANDBOX];
    // 国内访问苹果服务器比较慢，timeoutInterval需要长一点
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    request.HTTPMethod = @"POST";
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    
    NSString *payload = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", encodeStr];
    NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];
    
    request.HTTPBody = payloadData;
    // 提交验证请求，并获得官方的验证JSON结果
    //NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSOperationQueue *opQueue = [NSOperationQueue new];
    [NSURLConnection sendAsynchronousRequest:request queue:opQueue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        // 官方验证结果为空验证失败
        if (data == nil)
        {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"验证失败"];
            return;
        }
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if ([[dict objectForKey:@"status"] integerValue] == 0) {
            NSLog(@"购买成功");
            
            [MBProgressHUD hideHUD];
            [self addRoseApplePurchase];
        }else{
            
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"验证失败"];
        }
        
    }];

}
    




#pragma mark -
#pragma mark -充值金豆
/**
 充值金豆API
 */
-(void)addRoseApplePurchase
{
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    //时间戳
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *actionType = @"1";
    NSString *nat = [NSString stringWithFormat:@"%@%@%@%@%@",objID, uid, publicKey, actionType, sTime];
    nat = [nat md5Encrypt];
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    
    NSDictionary * applePayDic = [NSDictionary dictionaryWithObjectsAndKeys:uid,@"userid",locationString,@"timestamp",nat,@"appsign",actionType,@"transtype",self.payMoney,@"money",self.payOrder,@"payorder",nil];
    
    [BMHHTTPSession GET:@"/MobileInterface/Pay/applepay.ashx?" paraments:applePayDic success:^(id  _Nullable JSON) {
        
    [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
        
    } failure:^(NSError * _Nullable error) {
        
        
    }];
}

@end
